package com.zeus.gen.base.dto;

import com.zeus.gen.util.ConversionUtil;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author liuwei
 * @version 2017/9/5 下午5:42
 * @description 查询对象
 * @see
 * @since 1.0
 */
public class Query<T> {
    private boolean page = false;

    private Map<String, Object> params = new LinkedHashMap<>();
    private StringBuilder orderBy = new StringBuilder();

    public Query() {
    }

    public Query(boolean page) {
        this.page = page;
    }

    public Query<T> putAll(T bean) {
        try {
            if (bean == null) {
                return this;
            }
            params = ConversionUtil.conversionToMapExcludeEmpty(bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    /**
     * 单条加入查询条件
     *
     * @param key   字段名称
     * @param value 值
     * @return 查询条件
     */
    public Query<T> append(String key, Object value) {
        params.put(key, value);
        return this;
    }

    public Query<T> appendOrderBy(String param, OrderBy order) {
        if (orderBy.length() > 0) {
            orderBy.append(",");
        }
        orderBy.append(param);
        switch (order) {
            case DESC:
                orderBy.append(" desc");
                break;
            case ASC:
            default:
                orderBy.append(" asc");
                break;
        }
        return this;
    }

    public enum OrderBy {
        DESC, ASC;
    }

    public boolean isPage() {
        return page;
    }

    public void setPage(boolean page) {
        this.page = page;
    }

    public String getOrderBy() {
        return orderBy.toString();
    }

}
